package com.roden.study.algorithm.bit;

public class BtyeTest {
    /**
     * int整型转为byte字节
     */
    public static byte[] intTOBtyes(int in) {
        byte[] arr = new byte[4];
        for (int i = 0; i < 4; i++) {
            System.out.println(Integer.toBinaryString((in >> 8 * i) & 0xff));
            arr[i] = (byte) ((in >> 8 * i) & 0xff);
            System.out.println(Integer.toBinaryString(arr[i]));
        }
        return arr;
    }

    /**
     * byte字节转为int整型
     */
    public static int bytesToInt(byte[] arr) {
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += (int) (arr[i] & 0xff) << 8 * i;
        }
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(Integer.toBinaryString(0xff));
        System.out.println(Integer.toBinaryString(90328));
        System.out.println(Integer.toBinaryString(90328&0xff));
        System.out.println("-------------------------------------------");
        byte[] arr = intTOBtyes(90328);
        for (byte b : arr) {
            System.out.print(b + " ");
        }
        System.out.println();
        System.out.println(bytesToInt(arr));

        //字符串与字节数组
        String str = "有女如玉";
        byte[] barr = str.getBytes();

        String str2 = new String(barr);
        System.out.println("字符串转为字节数组：");
        for (byte b : barr) {
            System.out.print(b + " ");

        }
        System.out.println();
        System.out.println("字节数组换位字符串：" + str2);


    }

}
